package org.myorg.kafka2mysql.demo.mysql;


import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.myorg.kafka2mysql.demo.entitys.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

public class SinkListToMysql extends RichSinkFunction<List<Student>> {
	private PreparedStatement ps;
	private BasicDataSource dataSource;
	private Connection connection;

	/**
	 * open() 方法中建立连接，这样不用每次 invoke 的时候都要建立连接和释放连接
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void open(Configuration parameters) throws Exception {
		super.open(parameters);
		dataSource = new BasicDataSource();
		connection = getConnection(dataSource);
		String sql = "insert into student(id, name, password, age) values(?, ?, ?, ?);";
		ps = this.connection.prepareStatement(sql);
	}

	private Connection getConnection(BasicDataSource dataSource) {
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://10.10.87.38:3306/crm");
		dataSource.setUsername("crm");
		dataSource.setPassword("crm@2015");
		//设置连接池的一些参数
		dataSource.setInitialSize(2);
		dataSource.setMaxTotal(10);
		dataSource.setMinIdle(2);

		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (Exception e) {
			System.out.println("-----------mysql get connection has exception , msg = " + e.getMessage());
		}
		return conn;
	}

	@Override
	public void close() throws Exception {
		super.close();
		//关闭连接和释放资源
		if (connection != null) {
			connection.close();
		}
		if (ps != null) {
			ps.close();
		}
	}

	/**
	 * 每条数据的插入都要调用一次 invoke() 方法
	 *
	 * @param value
	 * @param context
	 * @throws Exception
	 */
	@Override
	public void invoke(List<Student> value, Context context) throws Exception {
		for (Student student : value) {
			ps.setInt(1, student.getId());
			ps.setString(2, student.getName());
			ps.setString(3, student.getPassword());
			ps.setInt(4, student.getAge());
			ps.addBatch();
		}
		int [] count = ps.executeBatch(); //批量后执行
		System.out.println("成功插入行数：" + count.length);
	}
}
